<template>
  <view class="page-main">
    <!-- <view class="use-template-btn" @click="showTemplatePopup">
      使用模板
      <u-icon name="arrow-right"></u-icon>
    </view> -->

    <div class="w100 f ac xc mt10r" style="box-sizing: border-box">
      <view class="tc btn mr20r" style="width: 100%" @click="showTemplatePopup">
        使用模板
      </view>
    </div>
    <view class="plan-name-section">
      <view class="input-wrapper">
        <text class="input-label">计划名称：</text>
        <input
          v-model="planName"
          placeholder="请输入计划名称"
          class="plan-name-input"
        />
      </view>
    </view>
    <div style="padding: 30rpx">
      <div v-for="(item, index) in dataList" :key="index">
        <view class="f ac xb mt20r">
          <view
            class="title f ac rds20r"
            style="background-color: #000; color: #fff;  width: 70%; height: 70rpx;"
            @click="startEditPurpose(index)"
          >
            <u-icon name="edit-pen"></u-icon>
            <div v-if="!item.isEditing">{{ item.purpose }}</div>
            <input
              v-else
              v-model="item.purpose"
              class="purpose-input"
              @blur="finishEditPurpose(index)"
              @click.stop
              ref="purposeInput"
            />
          </view>
          <view
            class="add"
            style="background-color: #000;border-radius: 20rpx; color: #fff; width: 30%; height: 70rpx; display: flex; align-items: center; justify-content: center;"
            @click="
              () => {
                actIndex = index;
                show2 = true;
              }
            "
          >
            添加动作
          </view>
        </view>
        <div v-if="item.exercises && item.exercises.length > 0">
          <view
            v-for="(exercise, eIndex) in item.exercises"
            :key="eIndex"
            class="f ac xb mt30r plan chooseitem mt20r"
            @click="edit(exercise, eIndex, index)"
          >
            <view class="exercise-name" style="flex: 1; text-align: center;">
              <text
                v-if="!exercise.isEditing"
                @click.stop="startEdit(index, eIndex)"
              >
                {{ exercise.name }}
              </text>
              <input
                v-else
                v-model="exercise.name"
                class="name-input"
                @blur="finishEdit(index, eIndex)"
                @click.stop
                ref="nameInput"
              />
            </view>
            <view class="f ac" style="flex: 1; text-align: center;">
              <div class="tc">{{ exercise.sets }} 组 X  {{ exercise.reps.count }}{{ getUnitLabel(exercise.reps.unit) }}</div>
        
            </view>
            <view style="flex: 1; text-align: center;">
              <div>{{ exercise.weighs }}</div>
            </view>
          </view>
        </div>
        <div v-else class="f ac xc mt30r plan chooseitem mt20r">暂无动作</div>
      </div>
      <div
        class="w100 f ac xc mt50r"
        style="padding: 0 10vw; box-sizing: border-box"
      >
        <view class="tc btn mr20r" style="width: 90%" @click="addmd">
          添加目的
        </view>
      </div>

      <view class="save-section">
        <button class="save-btn" @click="submitPlan">保存计划</button>
      </view>
    </div>
    <u-popup :show="show2" @close="resetForm" round>
      <view class="popup-content">
        <view class="form-item">
          <text class="label">动作名称：</text>
          <input
            v-model="form.name"
            placeholder="请输入动作名称"
            class="input-field"
          />
        </view>

        <view class="form-item">
          <text class="label">组数：</text>
          <input
            type="number"
            v-model="form.sets"
            placeholder="请输入组数"
            class="input-field-small"
          />
          <text class="unit-text">组</text>
        </view>

        <view class="form-item">
          <text class="label">次数：</text>
          <input
            type="number"
            v-model="form.reps.count"
            placeholder="请输入次数"
            class="input-field-small"
          />
          <picker
            mode="selector"
            :range="unitOptions"
            range-key="label"
            :value="unitIndex"
            @change="handleUnitChange"
            class="unit-picker"
          >
            <view class="picker-text">
              {{ unitOptions[unitIndex].label }}
              <u-icon name="arrow-down" size="24"></u-icon>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">重量：</text>
          <input
            v-model="form.weighs"
            placeholder="请输入重量"
            class="input-field"
          />
        </view>

        <view class="button-group">
          <button class="reset-btn" @click="resetForm">重置</button>
          <button class="confirm-btn" @click="adddz">确定</button>
        </view>
      </view>
    </u-popup>
    <u-popup :show="show" @close="show = false">
      <view style="padding: 30rpx">
        <view
          v-for="(item, index) in mdList"
          :key="index"
          class="chooseitem mb20r f ac xb"
          @click="selId = item.id"
        >
          <view v-if="!item.slot" class="bodyr f ac">
            <!--                      <div class="mr20r" style="background: #00C853;width: 100rpx;height: 100rpx;"></div>-->
            {{ item.title }}
          </view>
          <view v-else>
            <div class="f ac">
              自定义：
              <input v-model="answer" type="text" />
            </div>
          </view>
          <image
            v-if="selId == item.id"
            class="sinchoose-on"
            mode=""
            src="/static/chooseon.png"
          ></image>
          <view v-else class="sinchoose"></view>
        </view>
        <u-button text="确定" type="primary" @click="submit"></u-button>
      </view>
    </u-popup>
    <u-popup :show="showTemplate" @close="showTemplate = false" :round="10">
      <view class="template-popup">
        <!-- 在这里添加模板选择的内容 -->
        <view class="template-title tc mt20r">选择模板</view>

        <view class="template-list">
          <view
            class="template-card"
            v-for="(item, index) in templates"
            :key="index"
            @click="selectTemplate(item)"
          >
            <view class="card-content">

              <view class="info-section">
                <view class="template-name">
                  {{ item.planName || "训练计划模板" }}
                </view>
                <!-- <view class="trainer-info">
                <text class="trainer-name">教练：gaohao</text>
              </view> -->
                <view class="create-time">创建于 2024-03-21</view>
              </view>
            </view>
          </view>
        </view>
        <!-- 模板列表 -->
        <!-- <view class="template-list">
          <view
            v-for="(template, tIndex) in templates"
            :key="tIndex"
            class="template-item"
            @click="selectTemplate(template)"
          >
            <view class="template-card">
              <view class="template-name">
                {{ template.planName }}
              </view>
              <view class="template-description">
                {{ template.description }}  
              </view>
            </view>
          </view>
        </view> -->
      </view>
    </u-popup>
  </view>
</template>

<script>
import { addPlanIns, plan } from "../../api/fit";
export default {
  data() {
    return {
      id: 0,
      customerId: 0,
      planTplId: 0,
      planName: "", // 计划名称
      dataList: [
        {
          purpose: "热身",
          exercises: [],
        },
        {
          purpose: "正式训练",
          exercises: [],
        },
        {
          purpose: "放松拉伸",
          exercises: [],
        },
      ],
      actIndex: 0,
      editIndex: "",
      show: false,
      show2: false,
      form: {
        name: "",
        sets: "",
        reps: {
          unit: "c",
          count: "",
        },
        weighs: "",
        interval: 30,
      },
      planName: "传统动作上肢肌力",
      unitIndex: 0, // 当前选中的单位索引
      unitOptions: [
        { label: "次", value: "c" },
        { label: "秒", value: "s" },
        { label: "分", value: "m" },
      ],

      planName: "",
      showTemplate: false, // 是否显示模板弹窗
      templates: [], // 模板列表数据
      selectedTemplate: null, // 选中的模板
    };
  },
  onLoad(options) {
    console.log(options, "options");
    // 如果是从其他页面传入的参数，在这里获取
    if (options) {
      // this.customerId = Number(optionsthis.$u.test.digits()) || 0;
      this.customerId = options.id || 0;
    }
  },
  methods: {
    // 显示模板弹窗
    async showTemplatePopup() {
      const res = await plan();
      this.templates = res.data.list;
      this.showTemplate = true;
    },
    // 选择模板
    selectTemplate(template) {
      console.log(template, "template");
      this.dataList = template.nodes;
      this.selectedTemplate = template;
      this.showTemplate = false;
    },
    // 使用选中的模板
    useSelectedTemplate() {
      if (this.selectedTemplate) {
        // 在这里可以根据选中的模板进行相应的操作，如加载模板数据等
        console.log("使用模板：", this.selectedTemplate);
        // 关闭弹窗
        this.showTemplate = false;
      }
    },
    getUnitLabel(unit) {
      const option = this.unitOptions.find((opt) => opt.value === unit);
      return option ? option.label : "";
    },
    handleUnitChange(e) {
      this.unitIndex = e.detail.value;
      this.form.reps.unit = this.unitOptions[this.unitIndex].value;
    },
    // 编辑时设置确的单位索引
    edit(exercise, eIndex, purposeIndex) {
      this.actIndex = purposeIndex;
      this.editIndex = eIndex;
      // 保存原始名称
      exercise._originalName = exercise.name;
      this.form = { ...exercise };
      this.unitIndex = this.unitOptions.findIndex(
        (opt) => opt.value === exercise.reps.unit
      );
      this.show2 = true;
    },
    // 重置表单时也要重置单位索引
    resetForm() {
      this.form = {
        name: "",
        sets: "",
        reps: {
          unit: "c",
          count: "",
        },
        weighs: "",
        interval: 30,
      };
      this.unitIndex = 0;
      this.editIndex = "";
      this.show2 = false;
    },

    adddz() {
      if (!this.form.name) {
        uni.showToast({
          title: "请输入动作名称",
          icon: "none",
        });
        return;
      }

      if (this.editIndex !== "") {
        this.dataList[this.actIndex].exercises[this.editIndex] = {
          ...this.form,
        };
      } else {
        if (!this.dataList[this.actIndex].exercises) {
          this.dataList[this.actIndex].exercises = [];
        }
        this.dataList[this.actIndex].exercises.push({ ...this.form });
      }
      this.show2 = false;
      this.resetForm();
    },

    resetForm() {
      this.form = {
        name: "",
        sets: "",
        reps: {
          unit: "c",
          count: "",
        },
        weighs: "",
        interval: 30,
      };
      this.editIndex = "";
      this.show2 = false;
    },

    // 开始编辑动作名称
    startEdit(purposeIndex, eIndex) {
      this.$set(
        this.dataList[purposeIndex].exercises[eIndex],
        "isEditing",
        true
      );
      // 等待 DOM 更新后聚焦输入框
      this.$nextTick(() => {
        const input = this.$refs.nameInput;
        if (input && input.length > 0) {
          input[input.length - 1].focus();
        }
      });
    },

    // 完成编辑动作名称
    finishEdit(purposeIndex, eIndex) {
      const exercise = this.dataList[purposeIndex].exercises[eIndex];
      if (!exercise.name.trim()) {
        uni.showToast({
          title: "动作名称不能为空",
          icon: "none",
        });
        exercise.name = exercise._originalName || "未命名动作";
      }
      this.$set(exercise, "isEditing", false);
    },

    async submitPlan() {
      // 验证计划名称
      if (!this.planName.trim()) {
        uni.showToast({
          title: "请输入计划名称",
          icon: "none",
        });
        return;
      }

      // 验证数据
      if (
        this.dataList.some(
          (item) => !item.exercises || item.exercises.length === 0
        )
      ) {
        uni.showToast({
          title: "请为每个目的添加至少一个动作",
          icon: "none",
        });
        return;
      }

      // 构造提交数据
      const submitData = {
        customerId: this.customerId,
        // planTplId: this.planTplId,
        planName: this.planName.trim(),
        nodes: this.dataList.map((item) => ({
          purpose: item.purpose,
          exercises: item.exercises.map((exercise) => ({
            name: exercise.name,
            sets: Number(exercise.sets),
            reps: {
              unit: exercise.reps.unit,
              count: Number(exercise.reps.count),
            },
            weighs: exercise.weighs,
            interval: Number(exercise.interval || 30),
          })),
        })),
      };

      try {
        uni.showLoading({
          title: "保存中...",
        });

        // 这里调用你的接口
        const res = await addPlanIns(submitData);

        uni.hideLoading();
        if (res.code === 200) {
          uni.showToast({
            title: "保存成功",
            icon: "success",
          });
          // 延迟1.5秒后返回上一页
          setTimeout(() => {
            const pages = getCurrentPages();
            if (pages.length > 1) {
              uni.navigateBack();
            } else {
              // 如果已经是第一页，则跳转到指定页面，例如计划列表页
              uni.redirectTo({
                url: '/pages/plan/list'
              });
            }
          }, 1500);
        } else {
          throw new Error(res.message || "保存失败");
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: error.message || "保存失败",
          icon: "none",
        });
      }
    },

    addmd() {
      this.dataList.push({
        purpose: "自定义目的",
        exercises: [],
      });
    },

    // 开始编辑目的
    startEditPurpose(index) {
      this.$set(this.dataList[index], "isEditing", true);
      // 保存原始值
      this.$set(
        this.dataList[index],
        "_originalPurpose",
        this.dataList[index].purpose
      );

      // 等待 DOM 更新后聚焦输入框
      this.$nextTick(() => {
        const input = this.$refs.purposeInput;
        if (input && input.length > 0) {
          input[input.length - 1].focus();
        }
      });
    },

    // 完成编辑目的
    finishEditPurpose(index) {
      const item = this.dataList[index];
      if (!item.purpose.trim()) {
        uni.showToast({
          title: "目的不能为空",
          icon: "none",
        });
        item.purpose = item._originalPurpose || "未命名目的";
      }
      this.$set(item, "isEditing", false);
    },
  },
};
</script>

<style lang="scss">
.chooseitem {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border: 1px solid #ebebeb;
  border-radius: 20rpx;
  background: #fff;
  &:active {
    background: #fff;
  }
}

.sinchoose {
  width: 28rpx;
  height: 28rpx;
  margin-right: 16rpx;
  border-radius: 50%;
  background: #ffffff;
  border: 2rpx solid #bfbdbd;
}

.sinchoose2 {
  border-radius: 6rpx;
}

.sinchoose-on {
  width: 32rpx;
  height: 32rpx;
  margin-right: 16rpx;
}
.btn {
  padding: 30rpx;
  background: #000;
  color: #fff;
  border-radius: 30rpx;
}

.popup-content {
  padding: 30rpx;
  width: 600rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.label {
  width: 160rpx;
  font-size: 28rpx;
  color: #333;
}

.input-field {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.input-field-small {
  width: 120rpx;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  text-align: center;
}

.unit-text {
  margin-left: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.unit-picker {
  margin-left: 20rpx;
  width: 140rpx;
}

.picker-text {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 50rpx;
  padding: 0 30rpx;
}

.reset-btn,
.confirm-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.reset-btn {
  background: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: #000;
  color: #fff;
}

.save-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 40rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.save-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  background: #000;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 45rpx;
  letter-spacing: 2rpx;
}

/* 将嵌套的 &:active 改为独立的选择器 */
.save-btn:active {
  opacity: 0.9;
  transform: translateY(2rpx);
}

.page-main {
  padding-bottom: 130rpx;
}

.plan-name-section {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 16rpx;
}

.input-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 20rpx;
  white-space: nowrap;
}

.plan-name-input {
  flex: 1;
  height: 70rpx;
  font-size: 28rpx;
  padding: 0 20rpx;
  background: #fff;
  border-radius: 8rpx;
}

.exercise-name {
  position: relative;
  min-width: 200rpx;

  .name-input {
    width: 100%;
    height: 60rpx;
    padding: 0 20rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    font-size: 28rpx;
    background: #fff;
  }
}

.purpose-input {
  flex: 1;
  height: 60rpx;
  padding: 0 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
  margin: 0 12rpx;
}

.title {
  input {
    flex: 1;
    min-width: 120rpx;
  }
}

.template-list {
  padding: 10rpx;
}

.template-card {
  background: #fff;
  border-radius: 20rpx;
  margin-bottom: 24rpx;
  transform: translateY(0);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
  }

  .card-content {
    display: flex;
    padding: 24rpx;
    align-items: center;
  }

  .avatar-section {
    margin-right: 24rpx;

    .trainer-avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 16rpx;
      background: #f5f5f5;
    }
  }

  .info-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    min-height: 100rpx;

    .template-name {
      font-size: 32rpx;
      font-weight: 600;
      color: #000;
      margin-bottom: 12rpx;
    }

    .trainer-info {
      margin-bottom: 8rpx;

      .trainer-name {
        font-size: 26rpx;
        color: #666;
        background: #f8f8f8;
        padding: 4rpx 16rpx;
        border-radius: 6rpx;
      }
    }

    .create-time {
      font-size: 24rpx;
      color: #999;
    }
  }

  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.06);

    .trainer-avatar {
      transform: scale(1.02);
      transition: transform 0.3s ease;
    }
  }
}

.input-wrapper {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #000;
  border-radius: 16rpx;
}

.input-label {
  font-size: 40rpx;
  color: #fff;
  white-space: nowrap;
}
</style>
